import React, { useState } from "react";
import { Tabs, Form, Input, Button, message } from "antd";
import {
  MobileOutlined,
  UserOutlined,
  LockOutlined,
  MailOutlined,
  SyncOutlined,
} from "@ant-design/icons";
import "./index.css";
import {
  loginByAccount,
  loginByPhone,
} from "../../utils/redux/slices/authSlice";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";

const Login = () => {
  const [activeTab, setActiveTab] = useState("account");
  const [form] = Form.useForm();
  const [countdown, setCountdown] = useState(0);
  const [loading, setLoading] = useState(false);
  const dispatch = useDispatch();
  const navigate = useNavigate();

  // 处理获取验证码
  const handleGetCaptcha = () => {
    if (countdown > 0) return;

    form.validateFields(["phone"]).then((values) => {
      message.success(`验证码已发送至 ${values.phone}`);
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) clearInterval(timer);
          return prev > 0 ? prev - 1 : 0;
        });
      }, 1000);
    });
  };

  // 提交表单
  const handleSubmit = async (values) => {
    setLoading(true);
    if (activeTab === "account") {
      const flag = await dispatch(loginByAccount(values));
      if (flag) {
        navigate("/");
      }
    } else {
      const flag = await dispatch(loginByPhone(values));
      if (flag) {
        navigate("/");
      }
    }
    setLoading(false);
  };

  return (
    <div className="login-container">
      <div className="login-card">
        <h1 className="login-title">欢迎登录</h1>

        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          centered
          items={[
            {
              key: "account",
              label: "账号登录",
            },
            {
              key: "phone",
              label: "手机登录",
            },
          ]}
        />

        <Form
          form={form}
          initialValues={{
            account: "admin",
            password: "123456",
            phone: "12345678901",
          }}
          onFinish={handleSubmit}
        >
          {activeTab === "account" ? (
            <>
              <Form.Item
                name="account"
                rules={[{ required: true, message: "请输入用户名" }]}
              >
                <Input
                  prefix={<UserOutlined />}
                  maxLength={32}
                  placeholder="用户名"
                  className="custom-input"
                />
              </Form.Item>

              <Form.Item
                name="password"
                rules={[{ required: true, message: "请输入密码" }]}
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  maxLength={32}
                  placeholder="密码"
                  className="custom-input"
                />
              </Form.Item>
            </>
          ) : (
            <>
              <Form.Item
                name="phone"
                rules={[
                  { required: true, message: "请输入手机号" },
                  { pattern: /^1\d{10}$/, message: "手机号格式不正确" },
                ]}
              >
                <Input
                  prefix={<MobileOutlined />}
                  placeholder="手机号"
                  className="custom-input"
                />
              </Form.Item>

              <Form.Item
                name="captcha"
                rules={[
                  { required: true, message: "请输入验证码" },
                  { pattern: /^\d{6}$/, message: "验证码为6位数字" },
                ]}
              >
                <div className="captcha-container">
                  <Input
                    prefix={<MailOutlined />}
                    placeholder="验证码"
                    className="custom-input"
                  />
                  <Button
                    onClick={handleGetCaptcha}
                    disabled={countdown > 0}
                    className="captcha-button"
                  >
                    {countdown > 0 ? `${countdown}秒后重试` : "获取验证码"}
                  </Button>
                </div>
              </Form.Item>
            </>
          )}

          <Form.Item>
            <Button
              type="primary"
              loading={loading && { icon: <SyncOutlined spin /> }}
              htmlType="submit"
              className="login-button"
            >
              {activeTab === "account" ? "立即登录" : "手机快捷登录"}
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
